import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jetour_line/aha_jetour_line.dart';
import 'package:jetour_line/base_widget/base_image.dart';
import 'package:jetour_line/base_widget/base_scaffold.dart';
import 'package:jetour_line/base_widget/image_network_widget.dart';
import 'package:jetour_line/base_widget/loading_widget.dart';
import 'package:jetour_line/model/search_gao_list_model.dart';
import 'package:jetour_line/model/search_list_model.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/network/aha_http.dart';
import 'package:jetour_line/pages/baseWidget/title_widget.dart';
import 'package:jetour_line/pages/home/city_choose_page.dart';
import 'package:jetour_line/utils/extension_int.dart';
import 'package:jetour_line/utils/page_push_utils.dart';

import '../../base_widget/my_refresh_view.dart';
import '../../model/city_list_model.dart';

class SearchScreen extends StatefulWidget {
  const SearchScreen({
    Key? key,
  }) : super(key: key);

  @override
  State<SearchScreen> createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  int type = 2; //  1、酒店 2、景点 3、餐饮 4、其他（停车场，加油站，
  int page = 1;
  String city = '北京';
  int cityid = 400;
  List<ListElement> list = []; // 1、酒店 2、景点
  List<SearchGaoListModel> modelList = []; //3、餐饮 4、其他（
  final MyRefreshViewController _controller = MyRefreshViewController();
  String? keyWord;
  bool isRequest = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (AhaManger().searchCityName != null) {
      city = AhaManger().searchCityName!;
      cityid = AhaManger().searchCityId!;
    }
    search();
  }

  bool setCity = false;

  @override
  Widget build(BuildContext context) {
    setCity = true;

    int count = 0;
    if (type == 1 || type == 2) {
      count = list.length;
    } else {
      count = modelList.length;
    }
    return BaseScaffold(
        title: '搜索地点',
        body: Column(
          children: [
            Container(
              width: double.infinity,
              height: 100.px,
              alignment: Alignment.center,
              color: Colors.white,
              child: TitleWidget(
                const ['景点', '餐饮', '酒店', '其他'],
                selectIndexCallBack: (index) {
                  isRequest = false;
                  if (index == 0) {
                    type = 2;
                  } else if (index == 1) {
                    type = 3;
                  } else if (index == 2) {
                    type = 1;
                  } else if (index == 3) {
                    type = 4;
                  }
                  setState(() {

                  });
                  _controller.beginRef();
                },
              ),
            ),
            searchTitleWidget(),

            Expanded(
                child: Container(
              child:  MyRefreshView(
                refreshCallBack: (bool isUp) {
                  if (isUp) {
                    //下拉刷新
                    page = 1;
                  } else {
                    //上划加载更多
                    page++;
                  }
                  search();
                },
                controller: _controller,
                child:count == 0?Container(
                  width: double.infinity,
                  height: 800.px,
                  child: LoadingWidget(type: isRequest?1:0,),
                ): ListView.builder(
                    itemCount: count,
                    itemBuilder: (context, index) {
                      return itemWidget(index);
                    }),
              ),
            )),
          ],
        ));
  }

  Widget itemWidget(int index) {
    String url;
    String title = '西古堡村西古堡村西古堡村西古堡村西古堡村西古堡村';
    String subTitle = '张家口-蔚县-向军北里四巷10号圣天…张家口-蔚县-向军北里四巷10号圣天…';

    if (type == 1 || type == 2) {
      url = list[index].logo;
      title = list[index].caption;
      subTitle = list[index].address;
    } else {
      url = modelList[index].logo;
      title = modelList[index].caption;
      subTitle = modelList[index].address;
    }

    return Container(
      padding: EdgeInsets.only(left: 32.px, right: 32.px),
      width: double.infinity,
      height: 124.px,
      color: MyColors.white,
      child: Row(
        children: [
          ImageNetworkWidget(
            url,
            width: 120.px,
            height: 84.px,
            radius: 4.px,
          ),
          SizedBox(
            width: 20.px,
          ),
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                title,
                style: TextStyle(fontSize: 28.px, color: MyColors.color333333),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              SizedBox(
                height: 10.px,
              ),
              Text(
                subTitle,
                style: TextStyle(fontSize: 24.px, color: MyColors.color999999),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          )),
          GestureDetector(
            onTap: () {
              Map<String, dynamic> map = Map();
              map['type'] = type;
              if (type == 1 || type == 2) {
                map['nodeId'] = list[index].id;
              } else {
                SearchGaoListModel el = modelList[index];
                map['caption'] = title;
                map['images'] = modelList[index].images;
                map['logo'] = url;
                map['lnglat'] = '${el.geo.lng},${el.geo.lat}';
                map['address'] = el.address;
              }
              Navigator.pop(context, map);
            },
            child: Container(
              width: 96.px,
              height: 124.px,
              alignment: Alignment.center,
              color: Colors.transparent,
              child: BaseImage(
                image: 'lsgj_btn_add',
                width: 60.px,
                height: 60.px,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget searchTitleWidget() {
    return Container(
      padding: EdgeInsets.only(left: 32.px, right: 32.px),
      width: double.infinity,
      height: 100.px,
      color: MyColors.white,
      alignment: Alignment.center,
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(32.px)),
        child: Container(
          color: MyColors.colorF1F1F1,
          height: 64.px,
          child: Row(
            children: [
              GestureDetector(
                onTap: () {},
                child: Container(
                  color: Colors.transparent,
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          PagePushUtils.push(context, ChooseCityScreen())
                              .then((value) {
                            CityModel model = value as CityModel;
                            setState(() {
                              city = model.name;
                              cityid = model.id;
                            });
                            _controller.beginRef();
                            AhaManger().searchCityName = city;
                            AhaManger().searchCityId = cityid;
                          });
                        },
                        child: Container(color: Colors.transparent, child: Row(
                          children: [
                            SizedBox(
                              width: 26.px,
                              height: 64.px,
                            ),
                            Text(
                              city,
                              style: TextStyle(
                                  fontSize: 28.px, color: MyColors.color333333),
                            ),
                            SizedBox(
                              width: 8.px,
                            ),
                            BaseImage(
                              image: 'icon_meopen',
                              width: 28.px,
                              height: 28.px,
                            ),
                          ],
                        ),),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 15.px, right: 15.px),
                        width: 1.px,
                        height: 28.px,
                        color: MyColors.color999999,
                      ),
                      BaseImage(
                        image: 'ls_navbtn_search',
                        width: 40.px,
                        height: 40.px,
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                  child: TextField(
                onSubmitted: (value) {
                  keyWord = value;
                  _controller.beginRef();
                },
                onChanged: (value) {
                  keyWord = value;
                },
                style: TextStyle(fontSize: 28.px, color: MyColors.color333333),
                decoration: const InputDecoration(
                  border: InputBorder.none,
                  hintText: '请输入关键词',
                  isDense: true,
                  contentPadding: EdgeInsets.fromLTRB(8, 0, 0, 0),
                ),
              )),
              SizedBox(
                width: 26.px,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void search() {
    Map<String, dynamic>? params = {};
    if (keyWord != null) {
      params['keyword'] = keyWord;
    }
    params['page'] = page;
    params['size'] = 30;
    params['type'] = type;
    params['city'] = cityid;
    // params['lng'] = cityid;
    // params['lat'] = cityid;
    // print('searchsearchsearchsearch$params');
    if (type == 1 || type == 2) {
      AhaHttp().get(AhaRouter.LineToolPoiList, params: params).then((value) {

        isRequest = true;
        _controller.refreshEnd();
        SearchListModel model = SearchListModel.fromJson(value);
        if (page == 1) {
          list.clear();
        }
        list.addAll(model.list);
        setState(() {});
        FocusScope.of(context).unfocus();
      });
    } else {
      AhaHttp().get(AhaRouter.LineToolPoiInAmap, params: params).then((value) {
        print('searchsearchsearchsearch$value');
        isRequest = true;
        _controller.refreshEnd();
        List responseJson = value;
        List<SearchGaoListModel> model =
            responseJson.map((m) => SearchGaoListModel.fromJson(m)).toList();
        if (page == 1) {
          modelList.clear();
        }
        modelList.addAll(model);
        setState(() {});
        FocusScope.of(context).unfocus();
      });
    }
  }
}
